package com.yzy.demo;

import com.yzy.controller.CpuController;

import java.util.ArrayList;

public class Service {


    private ArrayList<Progress> progressList;

    public ArrayList<Progress> getProgressList() {
        return progressList;
    }

    //初始化进程
    public void init() {
        progressList = new ProgressList().getProgressList();
        for(Progress p:progressList) {
            p.finishTime = 0;
            p.totalTime = 0;
            p.weightTotalTime = 0;
        }
    }


    //先到先服务
    public ArrayList<Progress> FCFS(ArrayList<Progress> progressList) {
        int time = 0;
        for(int i=0;i<progressList.size();i++) {
            int flag = progressList.size();
            int compare = 100;
            for(Progress p:progressList) {
                if(p.finishTime==0) {
                    if(p.arriveTime<compare) {
                        compare = p.arriveTime;
                        flag = progressList.indexOf(p);
                    }
                }
            }

            //更新进程
            progressList.get(flag).finishTime = time + progressList.get(flag).runTime;
            progressList.get(flag).getTotalTime();
            progressList.get(flag).getWeightTotalTime();
            //更新时间
            time = progressList.get(flag).finishTime;
        }
        return progressList;
    }

    //短作业优先
    public ArrayList<Progress> SJF(ArrayList<Progress> progressList){
        int time = 0;
        for(int i=0;i<progressList.size();i++) {
            int flag = progressList.size();
            int compare = 100;
            for(Progress p:progressList) {
                //判断此时该进程是否到达
                if(p.arriveTime<=time) {
                    //判断该进程是否已完成
                    if(p.finishTime==0) {
                        //判断该进程运行时间是否最短
                        if(p.runTime<compare) {
                            compare = p.runTime;
                            flag = progressList.indexOf(p);
                        }
                    }
                }
            }

            //更新进程
            progressList.get(flag).finishTime = time + progressList.get(flag).runTime;
            progressList.get(flag).getTotalTime();
            progressList.get(flag).getWeightTotalTime();

            //更新时间
            time = progressList.get(flag).finishTime;
        }
        return progressList;
    }
}
